package com.hmdp.utils;

import cn.hutool.core.bean.BeanUtil;
import com.hmdp.dto.UserDTO;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.servlet.HandlerInterceptor;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @ClassName RefreshTokenInterceptor
 * @Author lidahu
 * @Description //TODO
 * @Date 2022/10/26 20:29
 **/
public class RefreshTokenInterceptor implements HandlerInterceptor {

    private StringRedisTemplate stringRedisTemplate;

    public RefreshTokenInterceptor(StringRedisTemplate stringRedisTemplate) {
        this.stringRedisTemplate = stringRedisTemplate;
    }

    //前置拦截器
    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //1.通过请求头获取token值拿到redis对应的value
        String tokenStr = request.getHeader("authorization");
        String token = RedisConstants.LOGIN_USER_KEY + tokenStr;
        //2.根据Token值从Redis中获取中的用户信息
        Map<Object, Object> map = stringRedisTemplate.opsForHash().entries(token);
        //将map值转换为UserDto
        UserDTO userDTO = BeanUtil.fillBeanWithMap(map, new UserDTO(), false);
        //5.保存用户信息到ThreadLocal
        UserHolder.saveUser(userDTO);
        //6.刷新有效期
        stringRedisTemplate.expire(token, 30, TimeUnit.MINUTES);
        return true;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        UserHolder.removeUser();
    }
}
